package com.dgut.usermodule.entity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

public class UserListDTO {
	private Long id;
	private String userName;
	private String phone;
	private String email;
	private Date date;
	public String getUserName() {
		return userName;
	}
	public String getPhone() {
		return phone;
	}
	public String getEmail() {
		return email;
	}
	public Date getDate() {
		return date;
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public static Specification<User> getSpecification(UserListDTO userListDTO){
		Specification<User> spec = new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(userListDTO != null && !StringUtils.isEmpty(userListDTO.getUserName())){
					Predicate p1 = cb.like(root.get("userName").as(String.class), "%"+userListDTO.getUserName()+"%");
					list.add(p1);
				}
				if(userListDTO != null && !StringUtils.isEmpty(userListDTO.getPhone())){
					Predicate p2 = cb.like(root.get("phone").as(String.class), "%"+userListDTO.getPhone()+"%");
					list.add(p2);
				}
				if(userListDTO != null && !StringUtils.isEmpty(userListDTO.getEmail())){
					Predicate p3 = cb.like(root.get("email").as(String.class), "%"+userListDTO.getEmail()+"%");
					list.add(p3);
				}
				if(userListDTO != null && !StringUtils.isEmpty(userListDTO.getDate())){
					Predicate p4 = cb.like(root.get("date").as(String.class), "%"+userListDTO.getDate()+"%");
					list.add(p4);
				}
				if(userListDTO != null && !StringUtils.isEmpty(userListDTO.getId())){
					Predicate p5 = cb.like(root.get("id").as(String.class), "%"+userListDTO.getId()+"%");
					list.add(p5);
				}
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
			
		};
		return spec;
	}
}
